package erfgame.core.world.terrain.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class BaseFileObjectDAO<T> {
	private Serializer<T> serializer;
	private FileStreamFactory streamFactory;
	
	public BaseFileObjectDAO( Serializer<T> serializer, FileStreamFactory streamFactory ) {
		this.serializer = serializer;
		this.streamFactory = streamFactory;
	}
	
	public T retrieveObject(File file, T into) {
		try {
			InputStream ins;
			ins = streamFactory.openInputStream( file );
			try {
				T result = serializer.retrieveObject(ins, into);
				return result;
			} finally {
				try {
					ins.close();
				} catch( IOException ex ) {
					ex.printStackTrace();
				}
			}
			
		} catch( Exception ex ) {
			throw new RuntimeException( "unable to read "+file.getPath(), ex );
		}
	}
		

	public void storeObject(File file, T object) {
		try {
			OutputStream outs = streamFactory.openOutputStream( file ); 
			try {
				serializer.storeObject( outs, object );
				outs.flush();
			} finally {
				try {
					outs.close();
				} catch( IOException ex ) {
					ex.printStackTrace();
				}
			}
		} catch( Exception ex ) {
			throw new RuntimeException( "unable to write "+object+" to "+file.getPath(), ex );
		}
	}
	

}
